<?php
include_once 'Zend/Auth.php';
class Auth extends Zend_Auth  
{
	/**
	 * Auth
	 *
	 * @var Auth
	 */
	protected static $_instance;
	
	/**
	 * Singleton Pattern
	 *
	 * @return Auth
	 */
	public static function getInstance()
	{
		if(self::$_instance == null){
			self::$_instance = new self();
		}
		
		return self::$_instance;
	}
	
	/**
     * $_tableName - the table name to check
     *
     * @var string
     */
	protected $_tableName = 'affiliSt_accounts';
	
    /**
     * $_identityColumn - the column to use as the identity
     *
     * @var string
     */	
	protected $_identityColumn = 'accUsername';
	
    /**
     * $_credentialColumn - columns to be used as the credentials
     *
     * @var string
     */
    protected $_credentialColumn = 'accPassword';
    
    /**
     * Zend_Auth_Adapter_DbTable
     *
     * @var Zend_Auth_Adapter_DbTable
     */
    protected $_adapter;
    
    public function __construct()
    {
    	include_once 'Zend/Registry.php';
    	$db = Zend_Registry::get('db');
    	include_once 'Zend/Auth/Adapter/DbTable.php';
    	$this->_adapter = new Zend_Auth_Adapter_DbTable($db, $this->_tableName, $this->_identityColumn, $this->_credentialColumn);
    	
    	include_once 'Zend/Auth/Storage/Session.php';
    	$storage = new Zend_Auth_Storage_Session('Auth');
    	$this->setStorage($storage);
    }

    /**
     * Chain of command pattern
     *
     * @param string $username
     * @return Auth
     */
    public function setIdentity($identity)
    {
    	$this->_adapter->setIdentity($identity);
    	return $this;
    }
    
    /**
     * Chain of command pattern
     *
     * @param string $password
     * @return Auth
     */
    public function setCredential($credential)
    {
    	$this->_adapter->setCredential(md5($credential));
    	return $this;
    }
    
    /**
     * Authenticates against the supplied adapter
     *
     * @param  Zend_Auth_Adapter_Interface $adapter
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {    
 		$result = parent::authenticate($this->_adapter);
 		if($result->isValid()){
 			// add this session in order to make affilistore know that this user has logged in
 		}
 		return $result;
    }
    
    public static function authenticated()
    {
    	return self::getInstance()->hasIdentity();	
    }
}
?>